# -*- coding: utf-8 -*-
from . import (
    api_app,
    request,
    response,
    json,
    re
)

from ...database.models.document import Document
from ...database.models.folder import Folder


@api_app.route('/document<:re:/?>', method=['POST'])
def create_document():
    title = request.params.getunicode('title', default=None, encoding='utf-8')
    content = request.params.getunicode('content', default=None, encoding='utf-8')
    parent = request.params.get('parent',None)
    doc_id = request.params.get('id', None)
    ret = None
     if not doc_id is None:
        mat = re.match(r'^[0-9a-f]{16}$', doc_id, re.IGNORECASE)
        if mat:
            pass
            oid = Document.id_hex2bin(doc_id)
            doc = None
            try:
                doc = db_client.connection.get(oid)
            except KeyError:
                pass
            if isinstance(doc, Document):
                # TODO: 更新数据到数据库
            else:
                ret = {
                    'error': 5,
                    'desc': '要更新的文档不存在'
                }
        else:
            ret = {
                'error': 4,
                'desc': '参数无效'
            }
    else:
        if bool(title):
            DBC = request.environ.pop('DBC')
            error = None
            data = None
            if parent is None:
                error, data = create_top_document(DBC, title, content)
            else:
                mat = re.match(r'^[0-9a-f]{16}$', parent, re.IGNORECASE)
                if mat:
                    error, data = create_children_document(DBC, title, content, parent)
                else:
                    ret = {
                        'error': 2,
                        'desc': '参数无效'
                    }
            if ret is None:
                if error is None:
                    ret = {
                        'error': 0,
                        'desc': None,
                        'data': data
                    }
                else:
                    ret = {
                        'error': 3,
                        'desc': error
                    }
        else:
            ret = {
                'error': 1,
                'desc': '缺少标题'
            }
    response.content_type = 'application/json'
    return json.dumps(ret)

@api_app.route('/document<:re:/?>', method=['GET'])
def list_document():
    DBC = request.environ.pop('DBC')
    ret = {}
    parent = request.params.get('parent', None)
    if parent is None:
        data = query_top_level(DBC)
        ret = {
            'error': 0,
            'desc': None,
            'data': data
        }
    else:
        mat = re.match(r'^[0-9a-f]{16}$', parent, re.IGNORECASE)
        if mat:
            data = query_children_level(DBC, parent)
            if data is None:
                ret = {
                    'error': 3,
                    'desc': '请求的目录不存在'
                }
            else:
                ret = {
                    'error': 0,
                    'desc': None,
                    'data': data
                }
        else:
            ret = {
                'error': 2,
                'desc': '参数无效'
            }
    response.content_type = 'application/json'
    return json.dumps(ret)

################################################################################
def query_top_level(db_client):
    '''获取顶级目录下的文档'''
    book_key = Document.book_key()
    book = db_client.root[book_key]
    # 根目录下的文档
    docs = [item for item in book if item.parent is None]
    # 对象转字典列表
    data = []
    for doc in docs:
        data.append(doc.toDict())
    return data

def query_children_level(db_client, parent):
    '''获取子目录下的文档(顶级目录下的，需指定父级目录id)'''
    oid = Folder.id_hex2bin(parent)
    node = None
    try:
        node = db_client.connection.get(oid)
    except KeyError:
        pass
    if isinstance(node, Folder):
        book_key = Document.book_key()
        book = db_client.root[book_key]
        docs = [item for item in book if item.parent == node]
        data = []
        for doc in docs:
            data.append(doc.toDict())
        return data
    else:
        return None

def create_top_document(db_client, title, content):
    '''创建顶级文档'''
    book_key = Document.book_key()
    book = db_client.root[book_key]
    error = None
    data = None
    existed = [item for item in book if item.parent is None and item.title == title]
    if bool(existed):
        error = '同标题的文档已存在'
    else:
        obj = Document(title, content)
        book.append(obj)
        db_client.root._p_changed = True
        db_client.commit()
        data = obj.toDict()
    return (error, data)

def create_children_document(db_client, title, content, parent):
    oid = Folder.id_hex2bin(parent)
    node = None
    try:
        node = db_client.connection.get(oid)
    except KeyError:
        pass
    error = None
    data = None
    if isinstance(node, Folder):
        book_key = Document.book_key()
        book = db_client.root[book_key]
        existed = [item for item in book if item.title == title and item.parent == node]
        if bool(existed):
            error = '同标题的文档已存在'
        else:
            obj = Document(title, content, node)
            book.append(obj)
            db_client.root._p_changed = True
            db_client.commit()
            data = obj.toDict()
    else:
        error = '目录不存在'
    return (error, data)